package com.atguigu.tingshu.dispatch.job;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.tingshu.model.dispatch.XxlJobLog;
import com.atguigu.tingshu.search.client.SearchFeignClient;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

@Component
public class SearchDispatchJobHandler {
    @Resource
    private SearchFeignClient searchFeignClient;
    @Resource
    private XxlJobLogMapper xxlJobLogMapper;

    @XxlJob("searchUpdateRankingData")
    public void searchUpdateRankingData() {
        long startTime = System.currentTimeMillis();
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        try {
            Result result = this.searchFeignClient.updateRankingData();
            if (result == null) {
                xxlJobLog.setStatus(0);
                xxlJobLog.setError("定时更新专辑热门数据时，远程调用接口失败！");
                XxlJobHelper.handleFail();
            } else {
                xxlJobLog.setStatus(1);
                XxlJobHelper.handleSuccess();
            }
        } catch (Exception e) {
            xxlJobLog.setStatus(0);
            xxlJobLog.setError("定时更新专辑热门数据时，服务器故障！");
            XxlJobHelper.handleFail();
            e.printStackTrace();
        } finally {
            xxlJobLog.setTimes(Long.bitCount(System.currentTimeMillis() - startTime));
            this.xxlJobLogMapper.insert(xxlJobLog);
        }
    }
}
